package com.capinfo.controller;

import com.alibaba.fastjson.JSONObject;
import com.capinfo.base.BaseController;
import com.capinfo.core.annotation.Log;
import com.capinfo.entity.SysDict;
import com.capinfo.entity.SysUser;
import com.capinfo.service.DictService;
import com.capinfo.util.JsonUtil;
import com.capinfo.util.ReType;
import com.capinfo.utils.RedisUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: sunbenjin
 * @date: 2020/2/29
 **/
@Controller
@RequestMapping(value="/dict")
public class SysDictController extends BaseController {

    @Autowired
    private DictService dictService;

    @Autowired
    private RedisUtils redisUtils;


    @GetMapping(value = "show")
    @RequiresPermissions("dict:show")
    public String show(Model model) {
        return "/system/dict/dict-list";
    }
    @ApiOperation(value = "/showDictList", httpMethod = "GET", notes = "展示字典列表")
    @GetMapping(value = "showDictList")
    @ResponseBody
    public ReType showDict(Model model, SysDict sysDict, String page, String limit) {
        if(StringUtils.isEmpty(page)){
            page = "0";
        }
        if(StringUtils.isEmpty(limit)){
            limit = "10";
        }
        return dictService.show(sysDict, Integer.valueOf(page), Integer.valueOf(limit));
    }
    @GetMapping(value = "addDict")
    @RequiresPermissions("dict:show")
    public String addDict(Model model, HttpServletRequest request,SysDict sysDict) {
        String pId = request.getParameter("pId");
        if(StringUtils.isNotEmpty(pId)){
            model.addAttribute("addChild","addChild");

            SysDict dict = dictService.selectByPrimaryKey(pId);
            sysDict.setParent(dict);


        }
        model.addAttribute("dict",sysDict);
        return "/system/dict/dict-form";
    }
    @GetMapping(value = "showDict")
    @RequiresPermissions("dict:show")
    public String showDict(Model model, HttpServletRequest request) {
       String id = request.getParameter("id");
       SysDict sysDict = dictService.selectByPrimaryKey(id);
       if(sysDict!=null){
           String pId = sysDict.getPId();
           if(!StringUtils.isEmpty(pId)){

               SysDict parent = dictService.selectByPrimaryKey(pId);
               sysDict.setParent(parent);
           }
       }
       String detail = request.getParameter("detail");
       model.addAttribute("detail",detail);
        model.addAttribute("dict",sysDict);
        return "/system/dict/dict-form";
    }
    @GetMapping(value = "addBrother")
    @RequiresPermissions("dict:addBrother")
    public String addBrother(Model model, HttpServletRequest request) {
        String id = request.getParameter("id");
        SysDict sysDict = dictService.selectByPrimaryKey(id);
        if(sysDict!=null){
            String pId = sysDict.getPId();
            if(!StringUtils.isEmpty(pId)){
                SysDict parent = dictService.selectByPrimaryKey(pId);
                sysDict.setParent(parent);
            }
        }
        String detail = request.getParameter("detail");
        model.addAttribute("detail",detail);
        sysDict.setId(null);
        sysDict.setDictName(null);
        sysDict.setDictValue(null);
        sysDict.setSort(null);
        model.addAttribute("dict",sysDict);
        return "/system/dict/dict-form";
    }
    @GetMapping(value = "addChild")
    @RequiresPermissions("dict:addChild")
    public String addChild(Model model, HttpServletRequest request) {
        String id = request.getParameter("id");
        SysDict sysDict = dictService.selectByPrimaryKey(id);

        SysDict child = new SysDict();
        child.setParent(sysDict);
        String detail = request.getParameter("detail");
        model.addAttribute("detail",detail);
        model.addAttribute("dict",child);
        return "/system/dict/dict-form";
    }
    @ApiOperation(value="addDict",httpMethod = "POST",notes="添加字典")
    @PostMapping("addDict")
    @ResponseBody
    public JsonUtil addDict(SysDict sysDict){
        JsonUtil j = new JsonUtil();
        try {
            if(StringUtils.isEmpty(sysDict.getId())){
                sysDict.setId(UUID.randomUUID().toString().replaceAll("-", ""));

                dictService.insertSelective(sysDict);
            }else{
                dictService.updateByPrimaryKeySelective(sysDict);
            }
//          删除redis缓存
            redisUtils.set(sysDict.getDictType()+sysDict.getDictValue(),sysDict);
            List<Object> redisList = redisUtils.lRange(sysDict.getDictType(),0,-1);
            if(!CollectionUtils.isEmpty(redisList)){
               List<SysDict> dictLists = (List<SysDict>)redisList.get(0);
               List<SysDict> collect = dictLists.stream().filter((dict)->!StringUtils.equals(dict.getId(),sysDict.getId())).collect(Collectors.toList());
               collect.add(sysDict);
               redisUtils.remove(sysDict.getDictType());
               redisUtils.lPush(sysDict.getDictType(),collect);
            }else{
                //没有这个字典，list添加
                List<SysDict> collect = new ArrayList<>();
                collect.add(sysDict);
                redisUtils.lPush(sysDict.getDictType(),collect);
            }
//            List<Object> collect = redisList.stream().filter((dict) -> StringUtils.equals(((SysDict) dict).getId(), sysDict.getId())).collect(Collectors.toList());
//            collect.add(sysDict);
//            redisUtils.remove(sysDict.getDictType());
//            redisUtils.lPush(sysDict.getDictType(),collect);
            j.setMsg("保存成功");
        } catch (Exception e) {
            j.setMsg("保存失败");
            j.setFlag(false);

            e.printStackTrace();
        }
        return j;
    }

    @GetMapping(value="checkValue")
    @ResponseBody
    public JsonUtil checkValue(String dictType,String dictValue,HttpServletRequest request){
        JsonUtil j = new JsonUtil();
        j.setFlag(Boolean.FALSE);
        if(StringUtils.isEmpty(dictType)||StringUtils.isEmpty(dictValue)){
            j.setMsg("获取数据失败");
            return j;
        }
        int result = dictService.checkValue(dictType,dictValue);
        if(result>0){
            j.setMsg("值已存在");
            return j;
        }
        j.setFlag(Boolean.TRUE);
        return j;
    }
    @ApiOperation(value="loadAllDict",httpMethod = "GET",notes="加载字典列表")
    @GetMapping(value="loadAllDict")
    @ResponseBody
    public JsonUtil loadAllDict(SysDict sysDict,HttpServletRequest request){
        JsonUtil j = new JsonUtil();

        try {

            List<SysDict> lists = dictService.selectListByPage(sysDict);;
            j.setFlag(Boolean.TRUE);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",lists);
            j.setJsonObj(jsonObject);
            System.out.println(j);
            j.setMsg("加载完成");
        } catch (Exception e) {
            j.setFlag(Boolean.FALSE);
            j.setMsg("加载异常");
            e.printStackTrace();
        }
        return j;
    }

    @Log(desc = "删除字典", type = Log.LOG_TYPE.DEL)
    @ApiOperation(value = "/del", httpMethod = "POST", notes = "删除用户")
    @PostMapping(value = "/del")
    @ResponseBody
    @RequiresPermissions("dict:del")
    public JsonUtil del(String id, boolean flag) {
        SysDict sysDict = dictService.selectByPrimaryKey(id);
        redisUtils.remove(sysDict.getDictType()+sysDict.getDictValue());
       List<Object> list =  redisUtils.lRange(sysDict.getDictType(),0,-1);
       if(!CollectionUtils.isEmpty(list)){
           List<SysDict> dictLists = (List<SysDict>)list.get(0);
           List<SysDict> collect = dictLists.stream().filter((dict)->!StringUtils.equals(dict.getId(),sysDict.getId())).collect(Collectors.toList());
          // collect.add(sysDict);
           redisUtils.remove(sysDict.getDictType());
           redisUtils.lPush(sysDict.getDictType(),collect);
       }

        return dictService.delById(id, flag);
    }
    @ApiOperation(value="loadDict",httpMethod = "GET",notes="加载特定类型的字典列表")
    @GetMapping(value="loadDict")
    @ResponseBody
    public JsonUtil loadDict(SysDict sysDict,HttpServletRequest request){
        JsonUtil j = new JsonUtil();

        try {
            List<Object> redisList = redisUtils.lRange(sysDict.getDictType(),0,-1);
            List<SysDict> dictLists = new ArrayList<>();
            if(!CollectionUtils.isEmpty(redisList)){
                dictLists = (List<SysDict>)redisList.get(0);
                dictLists.stream().sorted(Comparator.comparing(SysDict::getSort).reversed()).collect(Collectors.toList());
            }
            j.setFlag(Boolean.TRUE);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",dictLists);
            j.setJsonObj(jsonObject);
            System.out.println(j);
            j.setMsg("加载完成");
        } catch (Exception e) {
            j.setFlag(Boolean.FALSE);
            j.setMsg("加载异常");
            e.printStackTrace();
        }
        return j;
    }
    //从缓存中取字典名
    @ApiOperation(value="loadDictByTypeAndValue",httpMethod = "GET",notes="根据dict_type和dict_value加载字典名")
    @GetMapping(value="loadDictByTypeAndValue")
    @ResponseBody
    public JsonUtil loadDictByTypeAndValue(SysDict sysDict,HttpServletRequest request){
        JsonUtil j = new JsonUtil();

        try {
            String key = sysDict.getDictType()+sysDict.getDictValue();
//            String dictName = (String)redisUtils.get(key);
            SysDict dict = (SysDict)redisUtils.get(key);
            j.setFlag(Boolean.TRUE);
            JSONObject jsonObject = new JSONObject();
            if(dict==null){
                dict.setDictName("");
            }
            jsonObject.put("data",dict);
            j.setJsonObj(jsonObject);
            j.setMsg("加载完成");
        } catch (Exception e) {
            j.setFlag(Boolean.FALSE);
            j.setMsg("加载异常");
            e.printStackTrace();
        }
        return j;
    }


    @ApiOperation(value="loadSourceType",httpMethod = "GET",notes="pId加载所需材料")
    @GetMapping(value="loadSourceType")
    @ResponseBody
    public JsonUtil loadSourceType(SysDict sysDict,HttpServletRequest request){
        JsonUtil j = new JsonUtil();

        try {
            SysDict child = new SysDict();
            child.setPId(sysDict.getId());
            child.setDictType("source_type");
            List<SysDict> listChild = dictService.selectListByPage(child);
            if(!CollectionUtils.isEmpty(listChild)){
                j.setFlag(Boolean.TRUE);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("data",listChild);
                j.setJsonObj(jsonObject);
                System.out.println(j);
                j.setMsg("加载完成");
            }else{
                j.setFlag(Boolean.FALSE);
                j.setMsg("无材料需要上传");
            }
//            List<SysDict> listChild =

        } catch (Exception e) {
            j.setFlag(Boolean.FALSE);
            j.setMsg("加载异常");
            e.printStackTrace();
        }
        return j;
    }

    @ApiOperation(value="loadDictType",httpMethod = "GET",notes="加载所有字典类型")
    @GetMapping(value="loadDictType")
    @ResponseBody
    public JsonUtil loadDictType(HttpServletRequest request){
        JsonUtil j = new JsonUtil();

        try {
            SysDict child = new SysDict();
            List<SysDict> listChild = dictService.selectListByPage(child);
            List<SysDict> unique = new ArrayList<>();
            if(!CollectionUtils.isEmpty(listChild)){
//                listChild.stream().distinct()
                 unique = listChild.stream().filter(SysDict.distinctByKey(o->o.getDictType())).collect(Collectors.toList());
            }
//            Map<String,String> dictTypeMap = new HashMap<>();
//            if(!CollectionUtils.isEmpty(unique)){
//                for(SysDict dict:unique){
//                    dictTypeMap.put(dict.getDictType(),dict.getDictDesc());
//                }
//            }
            j.setFlag(Boolean.TRUE);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("data",unique);
            j.setJsonObj(jsonObject);
            System.out.println(j);
            j.setMsg("加载完成");
        } catch (Exception e) {
            j.setFlag(Boolean.FALSE);
            j.setMsg("加载异常");
            e.printStackTrace();
        }
        return j;
    }


}
